<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js';
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 10,
      total_count: 1,
      error: false,
    };
  },
  methods: {
    onLoad() {
      // 异步更新数据
      getSearchResult({
        q: this.searchText,
        page: this.page,
        per_page: this.per_page,
      })
        .then((res) => {
          this.list.push(...res.data.data.results);
          this.total_count = res.data.data.total_count;
          this.page = this.page + 1;
          // 加载状态结束
          this.loading = false;
        })
        .catch(() => {
          this.error = true;
          this.loading = false;
        });

      // 数据全部加载完成
      if (this.list.length >= this.total_count) {
        this.finished = true;
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
